#!/bin/bash

echo "Starting setup mongo replica set..."

mongodb1=mongostack_master
mongodb2=mongostack_secondary
mongodb3=mongostack_arbiter

echo "Waiting for  ${mongodb1} startup.."
until mongo --host ${mongodb1}:37017 --eval 'quit(db.runCommand({ ping: 1 }).ok ? 0 : 2)' &>/dev/null; do
  printf '.'
  sleep 1
done

echo "Waiting for  ${mongodb2} startup.."
until mongo --host ${mongodb2}:47017 --eval 'quit(db.runCommand({ ping: 1 }).ok ? 0 : 2)' &>/dev/null; do
  printf '.'
  sleep 1
done

echo "Waiting for  ${mongodb3} startup.."
until mongo --host ${mongodb3}:57017 --eval 'quit(db.runCommand({ ping: 1 }).ok ? 0 : 2)' &>/dev/null; do
  printf '.'
  sleep 1
done

echo "Mongo stack all started.."

echo setup.sh time now: `date +"%T" `
echo "Param values mongodb1=${mongodb1}, mongodb2=${mongodb2}, mongodb3=${mongodb3}, rs=${RS}  ..."

mongo --host ${mongodb1}:37017 --authenticationDatabase admin -u root -p admin@123 <<EOF
    var cfg = {
        "_id": "${RS}",
        "members": [
            {
                "_id": 0,
                "host": "${mongodb1}:37017",
                "priority" : 999
            },
            {
                "_id": 1,
                "host": "${mongodb2}:47017",
                "priority" : 1
            },
            {
                "_id": 2,
                "host": "${mongodb3}:57017",
                "priority" : 0,
                "arbiterOnly": true
            }
        ]
    };
    rs.initiate(cfg, { force: true });
    rs.reconfig(cfg, { force: true });
EOF

